package com.wu.controller;

import com.wu.entity.ShiroUser;
import com.wu.service.CompanyService;
import com.wu.service.MenuService;
import com.wu.service.impl.UserService;
import com.wu.util.EncryptUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/shiro")
public class LoginController extends BaseController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyService companyService;

    @RequestMapping(value = "/login", method = {RequestMethod.GET})
    public String login(HttpServletRequest request) {
        System.out.println("欢迎登陆！……");
        return "login";
    }

    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public String loginPost(ShiroUser user, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getPassword(), user.getIsRememberMe());

        String rememberMe = "on";
        if (user.getIsRememberMe() != null && rememberMe.equals(user.getIsRememberMe())) {
            //记住我功能
            token.setRememberMe(true);
        }

        try {
            System.out.println("loginPost token hash->" + token.hashCode());
            //用户认证
            currentUser.login(token);

        } catch (UnknownAccountException ex) {
            model.addAttribute("msg", ex.getMessage());
            return "login";
        } catch (IncorrectCredentialsException ice) {//凭据不正确，例如密码不正确 ...
            model.addAttribute("msg", "用户密码错误");
            return "login";
        } catch (LockedAccountException lae) { //用户被锁定，例如管理员把某个用户禁用...
            model.addAttribute("msg", lae.getMessage());
            return "login";
        } catch (ExcessiveAttemptsException eae) {//尝试认证次数多余系统指定次数 ...
            model.addAttribute("msg", "登录失败多次，账户锁定5分钟");
            return "login";
        } catch (AuthenticationException e) {
            System.out.println("登录失败");
            System.out.println(e);
            redirectAttributes.addFlashAttribute("msg", "用户名或密码错误！");
            model.addAttribute("msg", "用户名或密码错误！");
            return "login";
        }
        if (currentUser.isAuthenticated()) {

            //登录成功，保存用户相关信息
            sessionHandle(user, request);
            //跳转成功页面
            return "list";
        } else {
            redirectAttributes.addFlashAttribute("message", "用户名或密码错误！");
            return "login";
        }
    }


    @RequestMapping(value = "/register", method = {RequestMethod.POST})
    public String register(ShiroUser user,HttpServletRequest request,Model model) {
        String pwd = EncryptUtil.encrypt(user.getLoginName(), user.getPassword(), "MD5");
        user.setPassword(pwd);
        userService.insert(user);
        model.addAttribute("regMsg","注册成功");
        return "login";
    }

    private void sessionHandle(ShiroUser user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        ShiroUser loginUser = userService.getUserByLoginName(user.getLoginName());
        if (loginUser != null) {
            session.setAttribute("username", loginUser.getNickName());
            session.setAttribute("id", loginUser.getId());
        }
        //menuService.updateMenuInSession(request);
    }

}